<template>
  <Dialog
    v-model="show"
    :title="props.data?.id ? '编辑折扣活动' : '新增折扣活动'"
    width="600px"
    @close="close"
    @confirm="handleSubmit"
  >
    <div class="h-500 overflow-y-auto">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="活动名称" prop="activityName">
          <el-input
            v-model="formData.activityName"
            placeholder="请输入活动名称"
          />
        </el-form-item>

        <el-form-item label="选择店铺" prop="shopId">
          <el-select
            v-model="formData.shopId"
            filterable
            placeholder="请选择店铺"
            remote
            :remote-method="handleShopSearch"
            @change="handleShopChange"
          >
            <el-option
              v-for="item in shopOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="选择菜品" prop="products">
          <div class="d-flex align-items-center">
            <el-button type="primary" @click="openProductDialog"
              >选择菜品</el-button
            >
            <span v-if="formData.products.length" class="ml-2">
              已选菜品：{{ formData.products.length }}件
            </span>
          </div>
        </el-form-item>

        <el-form-item label="折扣" prop="discount">
          <el-input-number
            v-model="formData.discount"
            :min="0.1"
            :max="9.9"
            :precision="1"
            :step="0.1"
          />
        </el-form-item>

        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
            v-model="formData.activityTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
      </el-form>
    </div>
  </Dialog>

  <!-- 选择菜品弹窗 -->
  <Dialog
    v-model="productDialogVisible"
    title="选择菜品"
    width="800px"
    @confirm="confirmProducts"
  >
    <div class="mb-3 flex_aic_jcsb">
      <el-input
        v-model="productSearchKey"
        placeholder="请输入菜品名称"
        style="width: 300px"
        clearable
      />
      <el-button type="primary" @click="handleProductSearch">搜索</el-button>
    </div>

    <el-table :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column label="菜品图片" width="100">
        <template #default="{ row }">
          <el-image :src="row.image" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column prop="name" label="菜品名称" />
      <el-table-column prop="price" label="菜品价格" />
      <el-table-column prop="shopName" label="店铺名称" />
    </el-table>
    <div class="mt12 flex_aic_jcc">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next"
      />
    </div>
  </Dialog>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import Dialog from "@/components/dialog.vue";

const show = defineModel();
const emit = defineEmits(["success"]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(100)
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

// 表单数据
const formData = ref({
  activityName: "",
  shopId: "",
  products: [],
  discount: 9.9,
  activityTime: [],
});

// 表单校验规则
const rules = {
  activityName: [
    { required: true, message: "请输入活动名称", trigger: "blur" },
  ],
  shopId: [{ required: true, message: "请选择店铺", trigger: "change" }],
  products: [{ required: true, message: "请选择菜品", trigger: "change" }],
  discount: [{ required: true, message: "请输入折扣", trigger: "change" }],
  activityTime: [
    { required: true, message: "请选择活动时间", trigger: "change" },
  ],
};

// 店铺选项
const shopOptions = ref([
  {
    id: 1,
    name: "店铺1",
  },
  {
    id: 2,
    name: "店铺2",
  },
]);
// 菜品弹窗相关
const productDialogVisible = ref(false);
const productSearchKey = ref("");
const productList = ref(
  Array.from({ length: 10 }, (_, index) => ({
    id: index + 1,
    name: `菜品${index + 1}`,
    price: 100 + index,
    shopName: `店铺${index + 1}`,
    image: `https://picsum.photos/200/300?random=${index + 1}`,
  }))
);
const selectedProducts = ref([]);

const getStatusType = (status) => {
  const map = {
    1: "warning",
    2: "success",
    3: "danger",
  };
  return map[status];
};

watch(show, (val) => {
  if (val && props.data?.id) {
    // 编辑模式，加载数据
    formData.value = {
      ...props.data,
      activityTime: [props.data.startTime, props.data.endTime],
    };
  }
});

const formRef = ref();

// 处理店铺搜索
const handleShopSearch = async (query) => {
  // TODO: 实现店铺搜索逻辑
};

// 打开菜品选择弹窗
const openProductDialog = () => {
  productDialogVisible.value = true;
  // TODO: 加载菜品列表
};

// 处理菜品搜索
const handleProductSearch = () => {
  // TODO: 实现菜品搜索逻辑
};

// 处理菜品选择
const handleSelectionChange = (selection) => {
  selectedProducts.value = selection;
};

// 确认选择菜品
const confirmProducts = () => {
  formData.value.products = selectedProducts.value;
  productDialogVisible.value = false;
};

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        ...formData.value,
        startTime: formData.value.activityTime[0],
        endTime: formData.value.activityTime[1],
      };
      emit("success", submitData);
      close();
    }
  });
};

const close = () => {
  formData.value = {
    activityName: "",
    shopId: "",
    products: [],
    discount: 9.9,
    activityTime: [],
  };
  show.value = false;
};
</script>

<style lang="scss" scoped>
.h-500 {
  height: 500px;
}
.lht-38 {
  line-height: 38px;
}
.w-120 {
  width: 120px;
}
.mt24 {
  margin-top: 24px;
}
</style>
